//
//  RecommendViewController.m
//  CatMusic
//
//  Created by dllo on 15/4/21.
//  Copyright (c) 2015年 dllo. All rights reserved.
//

#import "RecommendViewController.h"
#import "NetWorkingTool.h"
#import "NetWorkingToolMv.h"
#import "SDCycleScrollView.h"
#import "UIImageView+WebCache.h"
#import "MyHeaderView.h"
#import "MycollectionCell.h"
#import "DetailViewController.h"
#import "MJRefresh.h"
#import "NightMode.h"
#import "RollPictureViewController.h"
#import "AFNetworkReachabilityManager.h"
#define HEIGHT self.view.frame.size.height
#define WIDTH self.view.frame.size.width
@interface RecommendViewController ()<SDCycleScrollViewDelegate,UIScrollViewDelegate,UICollectionViewDataSource,UICollectionViewDelegate,UICollectionViewDelegateFlowLayout>
{
    MyHeaderView *_headView;
}
@property(nonatomic, retain)UIScrollView *scrollView;
@property(nonatomic, retain)NSMutableArray *collectionArray;
@property(nonatomic, retain)UICollectionView *collectionView;
@property(nonatomic, copy) NSString *id;
@property(nonatomic, retain)NSMutableArray *content_idArray;
@property (nonatomic , retain)UIView *myView;
@property (nonatomic , retain)UIImageView *imageView;
@end

@implementation RecommendViewController
- (void)dealloc
{
    [_imageView release];
    [_myView release];
    [_content_idArray release];
    [_id release];
    [_collectionArray release];
    [_collectionView release];
    [_scrollView release];
    [super dealloc];
}

- (instancetype)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        self.collectionArray = [NSMutableArray array];
        self.content_idArray = [NSMutableArray array];
}
    return self;
}

- (void)viewDidLoad {
    [super viewDidLoad];
    self.title = @"推荐";
    // Do any additional setup after loading the view.
    self.view.backgroundColor = [UIColor cyanColor];
//    [self creatScrollView];
    
    [self creatCollectionView];

//    [self creatScrollView];
//    [self blockAsndGet];
//    [self newSongblockAsndGet];
//    [self creatCollectionView];

    
    
    
    
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(setLightDayModel) name:@"LightDayNSNotification" object:nil];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(setNightDayModel) name:@"NightDayNSNotification" object:nil];
    
    if ([NightMode shareNightMode].isNight) {
        [self setNightDayModel];
    } else {
        [self setLightDayModel];
    }
    
#pragma mark - 判断网络状态    AFN
    AFNetworkReachabilityManager *mgr = [AFNetworkReachabilityManager sharedManager];
    
    // 2.设置网络状态改变后的处理
    [mgr setReachabilityStatusChangeBlock:^(AFNetworkReachabilityStatus status) {
        // 当网络状态改变了, 就会调用这个block
        switch (status) {
            case AFNetworkReachabilityStatusUnknown: // 未知网络
                NSLog(@"未知网络");
                break;
                
            case AFNetworkReachabilityStatusNotReachable: // 没有网络(断网)
                NSLog(@"没有网络(断网)");
                [self alertViewCancel];
                break;
                
            case AFNetworkReachabilityStatusReachableViaWWAN: // 手机自带网络
                NSLog(@"手机自带网络");
                break;
                
            case AFNetworkReachabilityStatusReachableViaWiFi: // WIFI
                NSLog(@"WIFI");
                [self blockAsndGet];
                [self newSongblockAsndGet];
                [self mjRefresh];
                break;
        }
    }];
    
    // 3.开始监控
    [mgr startMonitoring];
    [self animationImage];
}


- (void)mjRefresh
{
    [self.collectionView addLegendHeaderWithRefreshingBlock:^{
        // 延迟加载数据，2秒后调用
        dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(2 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
            [self.collectionView reloadData];
            
            // 结束刷新
            [self.collectionView.header endRefreshing];
        });
        
    }];
}




- (void)alertViewCancel
{
    UIAlertView *alert = [[UIAlertView alloc]initWithTitle:@"提示" message:@"网络断开连接" delegate:self cancelButtonTitle:@"cancel" otherButtonTitles:nil, nil];
    [alert show];
}


- (void)animationImage
{
    self.myView = [[UIView alloc]initWithFrame:[[UIScreen mainScreen]bounds]];
    self.myView.backgroundColor = [UIColor whiteColor];
//    self.myView.alpha = 0.5;
    UILabel *label = [[UILabel alloc]initWithFrame:CGRectMake(WIDTH / 2 - 40, HEIGHT / 2 - 200, WIDTH / 375 * 160, HEIGHT / 667 * 40)];
    label.text = @"努力加载中....";
    [self.myView addSubview:label];
    [self.view addSubview:self.myView];
    self.imageView = [[UIImageView alloc]initWithFrame:CGRectMake(WIDTH / 2 -100, HEIGHT / 2 - 100, WIDTH / 375 * 200, HEIGHT / 667 * 200)];
    [self.myView addSubview:self.imageView];
    NSMutableArray *imageArr = [NSMutableArray array];
    for (NSInteger i = 1; i < 56 ; i++) {
        NSString *imageName = [NSString stringWithFormat:@"a%ld.png" , (long)i];
        UIImage *image = [UIImage imageNamed:imageName];
        [imageArr addObject:image];
    }
    self.imageView.animationImages = imageArr;
    self.imageView.animationDuration = 2.5;
    [self.imageView startAnimating];
    [_imageView release];
}










// // 轮播图的解析 使用
- (void)blockAsndGet
{
    [NetWorkingToolMv netWorkingToolStr:@"http://iting.music.189.cn:9200/iting2/imusic/V2?ids=banner_4,newsongalbum_3,selectedmv_4,recommendMusicPlayList_3,hotsong_10&protocolCode=2.0&method=get_gate_module_ios&sid=234472872&networkType=wifi&serviceCode=100&sessionId=83356C7DD4CDA5C8EE072C41746AA3A6&format=json&timestamp=20150424084717&sign=d68ad3aab1dd31af84e3e6a3da6dfb4e&imsi=87D618C0-A675-458D-BB55-BED13C712771&company=&appChannelCode=10000000&appVerCode=2.000.004" block:^(id result) {
        
        NSMutableDictionary *dictionary = result;
        NSMutableDictionary *datadic = [dictionary objectForKey:@"banner"];
        NSMutableArray *songlistsArray = [datadic objectForKey:@"data"];
        
        
        
        //        NSMutableDictionary *dictionary1 = [songlistsArray objectAtIndex:0];
        //        NSMutableArray *dataArray = [dictionary1 objectForKey:@"data"];
        NSMutableArray *imagesURL = [NSMutableArray array];
        
        
        for (NSMutableDictionary *dic in songlistsArray) {
            NSString *pic_url = [dic objectForKey:@"pic_url"];
            NSURL *url = [NSURL URLWithString:pic_url];
            [imagesURL addObject:url];
            
            NSString *content_id = [dic objectForKey:@"content_id"];
            [self.content_idArray addObject:content_id];
        }
        
        [imagesURL removeLastObject];
        
        
        //网络加载 --- 创建带标题的图片轮播器
        SDCycleScrollView *cycleScrollView2 = [SDCycleScrollView cycleScrollViewWithFrame:CGRectMake(0, 0, WIDTH - 40, HEIGHT  / 667 * 170) imageURLsGroup:nil];
        cycleScrollView2.autoScrollTimeInterval = 8.0;
        cycleScrollView2.pageControlAliment = SDCycleScrollViewPageContolAlimentCenter;
        cycleScrollView2.delegate = self;
        cycleScrollView2.layer.cornerRadius = 10;
        //    cycleScrollView2.titlesGroup = titles;
        cycleScrollView2.dotColor = [UIColor whiteColor]; // 自定义分页控件小圆标颜色
        [self.collectionView addSubview:cycleScrollView2];
        
        dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(2.0 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
            cycleScrollView2.imageURLsGroup = imagesURL;
        });
        
        
    }];
}





 // 轮播图要实现的协议
- (void)cycleScrollView:(SDCycleScrollView *)cycleScrollView didSelectItemAtIndex:(NSInteger)index
{
//    NSLog(@"---点击了第%ld张图片", index);
    
    RollPictureViewController *roll = [[RollPictureViewController alloc] init];
    roll.content_id = self.content_idArray[index];
    [self.navigationController pushViewController:roll animated:YES];
    [roll release];

    
}


//- (void)creatScrollView
//{
//    self.scrollView = [[UIScrollView alloc] initWithFrame:CGRectMake(0, 0, self.view.frame.size.width, self.view.frame.size.height)];
//    self.scrollView.contentSize = CGSizeMake(self.view.frame.size.width, self.view.frame.size.height * 2);
//    [self.scrollView setDelegate:self];
//    [self.view addSubview:self.scrollView];
//    self.scrollView.scrollEnabled = NO;
//}


// 排行榜数据解析
- (void)newSongblockAsndGet
{
    [NetWorkingTool netWorkingToolStr:@"http://v1.ard.tj.itlily.com/ttpod?a=getnewttpod&id=281&app=ttpod&v=v7.9.0.2015032618&uid=&mid=iPhone4S&f=f320&s=s310&imsi=&hid=4B0F54AF4D21&splus=5.1.1&active=0&net=2&openudid=d3f55133770025ed5e9b00d0f8a0d477137d44ce&idfa=&utdid=Uh6TqwnEHHIDAAJyziZDt9mr&alf=201200" block:^(id result) {

        NSMutableDictionary *dic = result;
        NSMutableArray *dataArray = [dic objectForKey:@"data"];
        
        for (NSMutableDictionary *dic in dataArray) {

            [self.collectionArray addObject:dic];
        }
        [self.collectionView reloadData];
    }];
}



- (void)creatCollectionView
{
    
    UICollectionViewFlowLayout *flowLayout = [[UICollectionViewFlowLayout alloc] init];
    flowLayout.itemSize = CGSizeMake(self.view.frame.size.width / 4, self.view.frame.size.width / 4 );
    self.collectionView = [[UICollectionView alloc] initWithFrame:CGRectMake(20, 0, self.view.frame.size.width - 40, HEIGHT - 70) collectionViewLayout:flowLayout];
    [self.view addSubview:_collectionView];
    [self.collectionView setBackgroundColor:[UIColor cyanColor]];
    [self.collectionView registerClass:[MycollectionCell class] forCellWithReuseIdentifier:@"cell"];
    [self.collectionView setDataSource:self];
    [self.collectionView setDelegate:self];
    [self.collectionView release];
    [self.collectionView setBackgroundColor:[UIColor clearColor]];
    
//    // 页眉注册
//    [self.collectionView registerClass:[MyHeaderView class] forSupplementaryViewOfKind:UICollectionElementKindSectionHeader withReuseIdentifier:@"Header"];
    
}


 // 设置页眉尺寸
- (CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout referenceSizeForHeaderInSection:(NSInteger)section
{
    CGSize size = {WIDTH, HEIGHT / 667 * 180};
    return size;
}


//- (UICollectionReusableView *)collectionView:(UICollectionView *)collectionView viewForSupplementaryElementOfKind:(NSString *)kind atIndexPath:(NSIndexPath *)indexPath
//{
//    MyHeaderView *headView;
//    if ([kind isEqual:UICollectionElementKindSectionHeader]) {
//        headView = [collectionView dequeueReusableSupplementaryViewOfKind:UICollectionElementKindSectionHeader withReuseIdentifier:@"Header" forIndexPath:indexPath];
////        headView.backgroundColor = [UIColor clearColor];
////        [headView setLabelText:[NSString stringWithFormat:@"section %ld header", (long)indexPath.section]];
//        [headView setLabelText:@"热歌排行"];
//    }
//
//    
//    return headView;
//    
//
//}


-(NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section
{

    return self.collectionArray.count;
    
}

-(UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath
{
    MycollectionCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:@"cell" forIndexPath:indexPath];
    cell.contentView.backgroundColor = [UIColor orangeColor];
    
    NSMutableDictionary *dic = self.collectionArray[indexPath.item];
    NSURL *url = [NSURL URLWithString:[dic objectForKey:@"big_pic_url"]];
    [cell.PhtotImage sd_setImageWithURL:url placeholderImage:[UIImage imageNamed:@"placeHolder"]];
    [self.myView removeFromSuperview];
    return cell;
    
}

- (void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath
{
//    NSLog(@"%ld", indexPath.item);
    DetailViewController *detail = [[DetailViewController alloc] init];
    [self.navigationController pushViewController:detail animated:YES];
    
   NSMutableDictionary *dic=  self.collectionArray[indexPath.row];
//    NSString *str = [dic objectForKey:@"title"];
//    NSLog(@"%@", str);
    detail.idNum = [dic objectForKey:@"id"];
    [detail release];
}


- (void)setLightDayModel
{
//    self.view.backgroundColor = [UIColor colorWithRed:216 / 255.0 green:247/ 255.0 blue:219 / 255.0 alpha:1];/////
    self.view.backgroundColor = [UIColor whiteColor];
     self.tabBarController.tabBar.barTintColor = [UIColor colorWithRed:245 / 255.0 green:241/ 255.0 blue:143 / 255.0 alpha:1];//////
    self.navigationController.navigationBar.barTintColor = [UIColor colorWithRed:245 / 255.0 green:241/ 255.0 blue:143 / 255.0 alpha:1];//////
    
    UIColor * color = [UIColor blackColor];
    //这里我们设置的是颜色，还可以设置shadow等，具体可以参见api
    NSDictionary * dict = [NSDictionary dictionaryWithObject:color forKey:NSForegroundColorAttributeName];
    //大功告成
    self.navigationController.navigationBar.titleTextAttributes = dict;
}

- (void)setNightDayModel
{
    self.view.backgroundColor = [UIColor colorWithRed:38 / 255.0 green:38/ 255.0 blue:38 / 255.0 alpha:1];
    self.tabBarController.tabBar.barTintColor = [UIColor blackColor];
    self.navigationController.navigationBar.barTintColor = [UIColor colorWithRed:38 / 255.0 green:38/ 255.0 blue:38 / 255.0 alpha:1];
    
    UIColor * color = [UIColor whiteColor];
    //这里我们设置的是颜色，还可以设置shadow等，具体可以参见api
    NSDictionary * dict = [NSDictionary dictionaryWithObject:color forKey:NSForegroundColorAttributeName];
    //大功告成
    self.navigationController.navigationBar.titleTextAttributes = dict;

}





- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
